import simplejson
import traceback
import logging
import datetime

from django.http import HttpResponse
from django.contrib.csrf.middleware import csrf_exempt


from lyricsplit.models import LyricLine,LyricLrc,EmoAnno

kid = 'mima1234'
def export_lrc_keys(request):
    if not request.GET.has_key('kid') or \
            request.GET['kid'] != kid:
        return HttpResponse("[]")
    klist = []
    for ll in LyricLrc.all():
        klist.append(
                (str(ll.key()),ll.name))
    return HttpResponse(simplejson.dumps(klist))

def export_anno_by_key(request):
    if not request.GET.has_key('kid') or \
            request.GET['kid'] != kid:
        return HttpReponse("[]")


    key = request.GET['key']
    lrc = LyricLrc.get(key)
    ll_list = []
    for lline in LyricLine.all().filter("lrc =",lrc).order('time'):
        tmp_dic = {}
        tmp_dic['key'] = str(lline.key())
        tmp_dic['line'] = lline.line
        tmp_dic['split_anno'] = lline.split_anno
        tmp_dic['time'] = lline.time
        tmp_dic['anno_dt'] = str(lline.anno_dt)
        ll_list.append(tmp_dic)
    return HttpResponse(simplejson.dumps(ll_list))

def export_emo_anno(request):
    start_d = request.GET['start']
    end_d = request.GET['end']
    start_dt = datetime.datetime(int(start_d[:4]),int(start_d[4:6]),int(start_d[6:8]))
    end_dt = datetime.datetime(int(end_d[:4]),int(end_d[4:6]),int(end_d[6:8]))

    ea_list = []
    for ea in EmoAnno.all().filter("anno_dt >=",start_dt).filter("anno_dt <=",end_dt):
        try:
            ea_list.append(
                (
                    str(ea.lrc.key()),
                    ea.emo,
                    ea.anno_desc,
                    ea.anno_ip,
                    str(ea.anno_dt),
                    str(ea.key())
                    )
                )
        except Exception,e:
            #print e
            logging.debug(str(e))
    return HttpResponse(simplejson.dumps(ea_list))
